import React, { Fragment, Component } from 'react';
import styles from './index.less';
import { connect } from 'dva';
import { Table, Popconfirm, Form, Button, Divider, Input, InputNumber, Radio } from 'antd';
import  AddUserForm  from './AddUserForm';

const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
const FormItem = Form.Item;
const EditableContext = React.createContext();
const EditableRow = ({ form, index, ...props }) => (
    <EditableContext.Provider value={form}>
        <tr {...props} />
    </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

const EditableCell = ({ ...props }) => {
    const { editing, dataIndex, title, inputType, record, index, editType, ...restProps } = props;
    const getInput = () => {
        if (inputType === 'number') {
            return <InputNumber />;
        } else if (inputType === 'radio') {
            return (
                <RadioGroup>
                    <RadioButton value={1}>普通</RadioButton>
                    <RadioButton value={2}>高级</RadioButton>
                </RadioGroup>
            );
        } else { return <Input /> }
    };
    return (
        <EditableContext.Consumer>
            {(form) => {
                const { getFieldDecorator } = form;
                return (
                    <td {...restProps}>
                        {editing ? (
                            dataIndex !== 'phone' ? (
                                <FormItem style={{ margin: 0 }}>
                                    {getFieldDecorator(dataIndex, {
                                        rules: [{
                                            required: true,
                                            message: `请输入${title}!`,
                                        }],
                                        initialValue: editType === 'addMoney' && dataIndex === 'restMoney' ? 0 : record[dataIndex],
                                    })(getInput())}
                                </FormItem>) : (
                                <FormItem style={{ margin: 0 }}>
                                    {getFieldDecorator(dataIndex, {
                                        rules: [{
                                            required: true,
                                            message: `请输入${title}!`,
                                        },
                                        {
                                            pattern: /^1\d{10}$/,
                                            message: '手机号格式错误！',
                                        }
                                        ],
                                        initialValue: record[dataIndex],
                                    })(getInput())}
                                </FormItem>
                            )
                        ) : restProps.children}
                    </td>
                );
            }}
        </EditableContext.Consumer>
    );
};

@connect(({ user, loading }) => ({
    userList:user.userList,
    loading: loading.effects['user/editUser', 'user/addMoney', 'user/queryUser'],
    loadingEdit: loading.effects['user/addUser'],
})) //eslint-disable-line
class UserList extends Component {
    state={
        visible: false,
        editingKey: '',
        editType: ''
    }
    componentDidMount() {
        const { dispatch } = this.props;
        dispatch({
            type: 'user/queryUser'
        });
    }
    deleteUser(id) {
        const { dispatch } = this.props;
        dispatch({
            type: 'user/deleteUser',
            payload: id
        });
    }
    handleAdd() {
        const { form } = this.formRef.props;
        const { dispatch } = this.props;
        form.validateFields((err, values) => {
            if (err) return;
            dispatch({
                type: 'user/addUser',
                payload: {
                    user: { ...values, phone: Number(values.phone) }
                }
            }).then(() => {
                form.resetFields();
                this.setState({
                    visible: false
                });
                dispatch({
                    type: 'user/queryUser'
                });
            });
        });

    }
    handleCancel() {
        this.setState({
            visible: false,
        });
    }
    showModal() {
        this.setState({
            visible: true
        });
    }
    saveFormRef = (formRef) => {
        this.formRef = formRef;
    }
    isEditing = (record) => {
        return record.id === this.state.editingKey;
    }
    edit(key, editType) {
        this.setState({
            editingKey: key,
            editType,
        });
    }
    save(form, record) {
        form.validateFields((error, row) => {
            if (error) { return }
            const { editType } = this.state;
            const { dispatch } = this.props;
            const { phone } = record;
            if (editType === 'edit') {
                dispatch({
                    type: 'user/editUser',
                    payload: {
                        phone,
                        user: {
                            ...row,
                            phone: Number(row.phone)
                        }
                    }
                }).then(() => {
                    this.setState({
                        editingKey: '',
                        editType: ''
                    });
                });
            } else {
                dispatch({
                    type: 'user/addMoney',
                    payload: {
                        phone,
                        money: Number(row.restMoney)
                    }
                }).then(() => {
                    this.setState({
                        editingKey: '',
                        editType: ''
                    });
                });
            }
        });
    }
    cancel=() => {
        this.setState({
            editingKey: '',
            editType: ''
        });
    }
    render() {
        const { userList, loading, loadingEdit } = this.props;
        const { visible, editType } = this.state;
        const components = {
            body: {
                row: EditableFormRow,
                cell: EditableCell,
            }
        };
        const columns = [{
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            editable: editType !== 'addMoney'
        },
        {
            title: '手机',
            dataIndex: 'phone',
            key: 'phone',
            editable: editType !== 'addMoney'
        },
        {
            title: editType === 'addMoney' ? '充值金额' : '账户余额',
            dataIndex: 'restMoney',
            key: 'restMoney',
            editable: true
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            render: (text) => (<span>{!text ? '其他' : Number(text) === 1 ? '普通' : Number(text) === 2 ? '高级' : '其他'}</span>),
            editable: editType !== 'addMoney'
        },
        {
            title: '车牌',
            dataIndex: 'vehicleLicense',
            key: 'vehicleLicense',
            editable: editType !== 'addMoney'
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: 160,
            render: (text, record) => {
                const editable = this.isEditing(record);
                return (
                    <div>
                        {editable ? (
                            <span>
                                <EditableContext.Consumer>
                                    {form => (
                                        <a
                                            onClick={() => this.save(form, record)}
                                            style={{ marginRight: 8 }}
                                        >
                                            保存
                                        </a>
                                    )}
                                </EditableContext.Consumer>
                                <Popconfirm
                                    title="确定取消?"
                                    onConfirm={() => this.cancel(record.id)}
                                >
                                    <a>取消</a>
                                </Popconfirm>
                            </span>
                        ) : (
                            <Fragment>
                                <a onClick={() => this.edit(record.id, 'edit')}>修改</a>
                                <Divider type="vertical" />
                                <a onClick={() => this.edit(record.id, 'addMoney')}>充值</a>
                                <Divider type="vertical" />
                                <Popconfirm
                                    title={(<Fragment>确定删除用户{`${record.name || ''}`}?</Fragment>)}
                                    onConfirm={() => this.deleteUser(record.id)}
                                >
                                    <a>删除</a>
                                </Popconfirm>
                            </Fragment>
                        )}
                    </div>
                );
            },
        }

        ];
        const EditableColumns = columns.map((col) => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    inputType: col.dataIndex === 'restMoney' ? 'number' : col.dataIndex === 'type' ? 'radio' : 'text',
                    title: col.title,
                    dataIndex: col.dataIndex,
                    editing: this.isEditing(record),
                    editType,
                })
            };
        });
        return (
            <div className={styles.container}>
                <Button onClick={this.showModal.bind(this)} loading={loadingEdit} type="primary" style={{ marginBottom: 16 }}>
                    新增用户
                </Button>
                <Table
                    components={components}
                    bordered
                    loading={loading}
                    dataSource={userList}
                    columns={EditableColumns}
                    rowKey={(record) => record.id}
                ></Table>
                <AddUserForm
                    loading={loadingEdit}
                    wrappedComponentRef={this.saveFormRef.bind(this)}
                    visible={visible}
                    onCancel={this.handleCancel.bind(this)}
                    onCreate={this.handleAdd.bind(this)}
                >
                </AddUserForm>
            </div>
        );
    }
}

export default UserList;
